package com.mc.developmentkit.utils;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import com.mc.developmentkit.activitys.UserCenterActivity;
import com.mc.developmentkit.bean.ThirdLoginInfo;
import com.mc.developmentkit.bean.UserInfo;
import com.mc.developmentkit.callback.LoginListener;
import com.mc.developmentkit.config.MCConstant;
import com.mc.developmentkit.https.HttpUtils;
import com.mc.developmentkit.json.Json;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.ex.DbException;

/**
 * Created by LeBron on 2017/1/3.
 */

public class Primary implements LoginListener {

    private Activity context;
    private String loginType;

    public Primary(Activity context, String loginType) {
        this.context = context;
        this.loginType = loginType;
    }

    @Override
    public void loginResult(String json) {
        ThirdLoginInfo thirdLoginInfo = Json.DNSThirdLogin(loginType, json);
        if (thirdLoginInfo!=null){
            try {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("nickname",thirdLoginInfo.nickname);
                jsonObject.put("unionid",thirdLoginInfo.id);
                jsonObject.put("head_icon",thirdLoginInfo.icon);
                jsonObject.put("third_login_type",loginType);
                HttpUtils.POST(mHandler, MCConstant.getUserThirdLoginUrl(),jsonObject.toString(),true);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else{
            ToastUtil.showToast("第三方登录返回数据为空");
        }

    }

    android.os.Handler mHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    UserInfo userInfo = Json.DNSLogin("登录",msg.obj.toString());
                    if (userInfo != null) {
                        DbManager db = DbUtils.getDB();
                        try {
                            db.saveOrUpdate(userInfo);
                            context.startActivity(new Intent(context, UserCenterActivity.class));
                            context.finish();
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                    } else {
                        ToastUtil.showToast("用户信息为空");
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;

            }
        }
    };

}
